package com.atguigu.ossservice.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.atguigu.ossservice.service.FileService;
import com.atguigu.ossservice.utils.ConstantPropertiesUtil;
import com.atguigu.servicebase.handler.GuliException;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Auther 赵乾坤
 * @Date 2021-06-30 21:58
 * 阿里云 1ID 2Secret
 * LTAI4GKVG6ZjcLpmQpWoMFmg
 * EAsw6cjn7j4YcrshYZ6SGTdsyk51pC
 */
@Service
public class FileServiceImpl implements FileService {


    @Override
    //上传文件
    public String uploadFileOSS(MultipartFile file)  {
        //不知道怎么办 ？ 看官方文档教学 ：简单上传文
        //获取阿里云存储相关常量

        //优化----不同生产环境 提出参数 因为有不同环境，根据配置文件改
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        String fileHost = ConstantPropertiesUtil.FILE_HOST;

          try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

           // 上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //uuid+01.jpg
            fileName = UUID.randomUUID().toString()+fileName;
            //构建日期路径：avatar/2019/02/26/文件名   ---根据pom文件的日期工具joda-time----格式"yyyy/MM/dd"
            String filePath = new DateTime().toString("yyyy/MM/dd");
            //优化文件名 不能重名
            fileName = filePath+"/"+fileName;
           //上传对象
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://guli-file200522test1.oss-cn-beijing.aliyuncs.com/01.jpg
            String url =fileHost+bucketName+"."+endpoint+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            //自定义异常
            throw new GuliException(20001,"上传失败");
        }
    }
}
